package Controller;

import java.io.File;
import java.io.IOException;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;

public class Mp3SamplePlayer {

	public void playFile(String fileName) {
		AudioInputStream soundStream;
		AudioInputStream targetSoundStream;
		AudioFormat baseFormat;
		AudioFormat format;
		File soundFile = new File(fileName);
		try {
			soundStream = AudioSystem.getAudioInputStream(soundFile);
			baseFormat = soundStream.getFormat();
			format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
					baseFormat.getSampleRate(), 16, baseFormat.getChannels(),
					baseFormat.getChannels() * 2, baseFormat.getSampleRate(),
					false);
			targetSoundStream = AudioSystem.getAudioInputStream(format,
					soundStream);
			rawplay(format, targetSoundStream);
			soundStream.close();
		} catch (UnsupportedAudioFileException e) {
			e.printStackTrace();
		} catch (LineUnavailableException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void rawplay(AudioFormat targetFormat,
			AudioInputStream targetSoundStream) throws IOException,
			LineUnavailableException {
		int nBytesRead = 0;
		int nBytesWritten = 0;
		byte[] data = new byte[4096];
		SourceDataLine sourceLine;
		sourceLine = getLine(targetFormat);
		if (sourceLine != null) {
			sourceLine.start();
			while (nBytesRead != -1) {
				nBytesRead = targetSoundStream.read(data, 0, data.length);
				if (nBytesRead != -1)
					nBytesWritten = sourceLine.write(data, 0, nBytesRead);
			}
			sourceLine.drain();
			sourceLine.stop();
			sourceLine.close();
			targetSoundStream.close();
		}
	}

	private SourceDataLine getLine(AudioFormat audioFormat)
			throws LineUnavailableException {
		SourceDataLine res = null;
		DataLine.Info info;
		info = new DataLine.Info(SourceDataLine.class, audioFormat);
		res = (SourceDataLine) AudioSystem.getLine(info);
		res.open(audioFormat);
		return res;
	}
}
